package com.udata.server.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.appengine.api.datastore.Key;
import com.udata.server.PMF;
import com.udata.server.dao.StokeDao;
import com.udata.server.model.Stoke;
import com.udata.shared.exception.OperationException;
import com.udata.shared.model.StokeB;

public class StokeDaoImpl extends StokeDao {
	@Override
	public StokeB save(StokeB stokeB) throws OperationException {
		Stoke stoke = new Stoke(stokeB);

		try {
			stokeB = this.load(stokeB.getId());
			if (stokeB == null) {
				PersistenceManager pm = PMF.get().getPersistenceManager();
				pm.makePersistent(stoke);
				pm.close();
			} else {
				throw new OperationException(this.getClass().getCanonicalName()
						+ ".save\n" + "User already exist");
			}
		} catch (Exception e) {
			throw new OperationException(this.getClass().getCanonicalName()
					+ ".save\n" + e.getMessage());
		}
		return stoke.getBean();

	}

	@Override
	public StokeB load(Key id) throws OperationException {
		Stoke result = null;
		try {
			PersistenceManager pm = PMF.get().getPersistenceManager();
			result = pm.getObjectById(Stoke.class, id);
			pm.close();
			return result.getBean();
		} catch (Exception e) {
			System.out.println("Can not load user id=" + id);
			return null;
		}

	}

	@Override
	public List<StokeB> getAll() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Stoke.class);

		List<Stoke> stokes = (List<Stoke>) query.execute();
		List<StokeB> stokeBList = new ArrayList<StokeB>();
		for (Stoke stoke : stokes) {
			stokeBList.add(stoke.getBean());
		}
		return stokeBList;

	}
}
